package com.mujin.keji.collectionsystem.module.outboundtask.views;

import android.Manifest;
import android.app.ActivityManager;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.guideview.GuideView;
import com.guideview.GuideViewHelper;
import com.guideview.LightType;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.common.VisitStatusEnum;
import com.mujin.keji.collectionsystem.db.dao.VisitDao;
import com.mujin.keji.collectionsystem.db.dao.VisitRecordDao;
import com.mujin.keji.collectionsystem.db.database.AppDataBase;
import com.mujin.keji.collectionsystem.db.domain.SaveVisitRecordBean;
import com.mujin.keji.collectionsystem.db.domain.VisitApplyBean;
import com.mujin.keji.collectionsystem.db.domain.VisitCountBean;
import com.mujin.keji.collectionsystem.dialog.BaseNiceDialog;
import com.mujin.keji.collectionsystem.dialog.NiceDialog;
import com.mujin.keji.collectionsystem.dialog.ViewConvertListener;
import com.mujin.keji.collectionsystem.dialog.ViewHolder;
import com.mujin.keji.collectionsystem.module.login.dto.LoginDto;
import com.mujin.keji.collectionsystem.module.main.views.MainActivity;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.EmailsituationsAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.HouseapplianceAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.InnerdecorationseAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.LivingsituationsAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.RepaypowersAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.VisithousesSizeAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.VsitHouseAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.BoundTaskDto;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.UserBean;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.VisitCaseDto;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.VisitRecordDetailDto;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.VisithouseDto;
import com.mujin.keji.collectionsystem.module.outboundtask.viewmodel.BoundTaskListViewModel;
import com.mujin.keji.collectionsystem.module.outboundtask.viewmodel.PhotoViewModel;
import com.mujin.keji.collectionsystem.module.outboundtask.viewmodel.RecordViewModel;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.SaveVisitRecordVo;
import com.mujin.keji.collectionsystem.module.tripplan.views.BusListPlanActivity;
import com.mujin.keji.collectionsystem.module.tripplan.views.BusPlanDetailActivity;
import com.mujin.keji.collectionsystem.module.tripplan.views.TaskTripMapActivity;
import com.mujin.keji.collectionsystem.module.updata.dto.VisitUserDto;
import com.mujin.keji.collectionsystem.module.updata.views.UploadSingleUserActivity;
import com.mujin.keji.collectionsystem.net.NetworkUtil;
import com.mujin.keji.collectionsystem.permissions.PermissionUtils;
import com.mujin.keji.collectionsystem.permissions.PermissionsObserver;
import com.mujin.keji.collectionsystem.server.RecordServcie;
import com.mujin.keji.collectionsystem.utils.DateUtil;
import com.mujin.keji.collectionsystem.utils.DialogUtils;
import com.mujin.keji.collectionsystem.utils.DisplayUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.FileUtil;
import com.mujin.keji.collectionsystem.utils.ImageUtils;
import com.mujin.keji.collectionsystem.utils.NumberUtils;
import com.mujin.keji.collectionsystem.utils.RecorderUtil;
import com.mujin.keji.collectionsystem.utils.SPUtil;
import com.mujin.keji.collectionsystem.utils.ToastUtils;
import com.mujin.keji.collectionsystem.widget.CustomerLayoutStyle;
import com.mujin.keji.collectionsystem.widget.SelectAssistCommissionerWindow;
import com.mujin.keji.collectionsystem.widget.SelectTimeDailog;
import com.mujin.keji.collectionsystem.widget.SelectTypeDailog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 外访详情Activity界面
 *
 * @author weishixiong
 * @Time 2018-03-21
 */

public class BoundDetailActivity extends BaseActivity implements View.OnClickListener, BDLocationListener, VsitHouseAdapter.VsitHouseSelectListener, InnerdecorationseAdapter.InnerdecorationsSelectListener, HouseapplianceAdapter.HouseapplianceSelectListener, LivingsituationsAdapter.LivingsituationsSelectListener, VisithousesSizeAdapter.VisithousesSizeSelectListener, EmailsituationsAdapter.EmailsituationsSelectListener, RepaypowersAdapter.RepaypowersSelectListener, SelectTimeDailog.GetSelectTimeListener, SelectAssistCommissionerWindow.SelectAssistCommissioner, SelectTypeDailog.SelectTypeListener {
    private TextView tvPhoto;
    private TextView tvRecording;
    private final int FROM_CAPTURE = 10001;
    private final int FROM_ALBUM = 10002;
    private final String AUTHORITY = "com.mujin.keji.collectionsystem.fileprovider";
    private PhotoViewModel photoViewModel;
    private RecordViewModel recordViewModel;
    private boolean isStart;
    private RecorderUtil recorderUtil;
    private String fileAdress;//文件生成地址
    private VisitCaseDto visitCaseDto;//案件实体
    private String taskAdress;//外访城市-区（深圳南山  动态）
    private LinearLayout llRecord;
    private LinearLayout llPhoto;
    private TextView tvTopName;
    private TextView tvTopStatus;
    private TextView tvTopAccount;
    private ImageView ivRecord;
    private ImageView ivPhoto;
    private BoundTaskDto dto;
    private BoundTaskListViewModel boundTaskListViewModel;
    //外访详情
    private TextView tvVisitTime;//外访时间
    private TextView tvStopTme;//结束时间
    private TextView tvHelper;//协助专员
    private TextView tvAdressType;//地址类型
    private TextView tvVisitAddress;//外访地址
    private TextView tvVisitStatus;//外访情况
    private TextView tvNewPhone;//新联系方式
    private TextView tvNewAddress;//新联系地址
    private TextView tvVisitContent;//外访描述
    private TextView tvVisitHouse;//外访房屋
    private TextView tvDecorate;//室内装修
    private TextView tvHomeAppliance;//家用电器
    private TextView tvLivingSituation;//居住情况
    private TextView tvEmailSituation;//邮箱情况
    private TextView tvReimbursementAbility;//还款能力
    private TextView tvNeighborsDescribed;//邻居描述
    private RelativeLayout rlVisitAddress;
    private EditText etVisitAddress;
    private TextView tvDefault;
    private TextView tvCustom;
    private RelativeLayout rlStreetAddress;
    private Button btnVisitOk;
    private Button btnDetailOk;
    private ImageView ivNoYes;
    private EditText etVisitTime;
    private Button btnVisitSave;
    private EditText etStreetAddres;
    private TextView tvRelationShip;
    private SmartRefreshLayout srlToVisit;
    private SmartRefreshLayout srlVisitDetail;
    private LinearLayout rlBtnVisit;
    private RelativeLayout rlBtnDetail;
    private LinearLayout llParent;
    private RelativeLayout rlDescription;
    private TextView tvNextStep;
    private TextView tvIsSee;

    //外访详情
    private void initCase(final VisitCaseDto visitCaseDto) {
        this.dto = visitCaseDto.getDto();
        this.visitCaseDto = visitCaseDto;
        initCaseView(1000);
    }

    /**
     * 根据不同状态显示view
     */
    private void initCaseView(int code) {
        tvTopName.setText(visitCaseDto.getDto().getVisitName());
        tvRelationShip.setText("(" + visitCaseDto.getDto().getVisitRelation() + ")");
        tvTopAccount.setText(NumberUtils.twoDecimalPlaces(visitCaseDto.getDto().getLatestDebtMoney()));
        if (EmptyUtils.isNotEmpty(visitCaseDto.getDto().getStatus())) {
            if (visitCaseDto.getDto().getStatus() == 1) {
                /**
                 * 初始化待外访的ui视图
                 */
                initWaiteVisitView(code);
                /**
                 * 获取照片文件
                 */
                /**
                 * 获取录音文件
                 */
                getRecordFileCount();
            } else if (visitCaseDto.getDto().getStatus() == 2) {
                initHavedVisitView();
                /**
                 * 获取照片文件
                 */
                // getPhotoFileOunt();
                /**
                 * 获取录音文件
                 */
                getRecordFileCount();

            } else if (visitCaseDto.getDto().getStatus() == 3) {
                initFinishVisitView();
            }
        }
    }


    /**
     * 初始化完成外访UI
     */
    private void initFinishVisitView() {
        setrightImage(R.drawable.image_to_main, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CcsApplication.clearAllActivitys();
                startActivity(new Intent(BoundDetailActivity.this, MainActivity.class));
            }
        });
        tvRecording.setTextColor(Color.parseColor("#ff5d5d5d"));
        tvPhoto.setTextColor(Color.parseColor("#ff5d5d5d"));
        ivPhoto.setImageResource(R.drawable.image_photo_noable);
        ivRecord.setImageResource(R.drawable.image_record_noable);
        setrightTitle("", "#FFFFFF", null);
//        ivCall.setVisibility(View.GONE);
        srlVisitDetail.setVisibility(View.VISIBLE);
        srlToVisit.setVisibility(View.GONE);
        rlBtnDetail.setVisibility(View.GONE);
        rlBtnVisit.setVisibility(View.GONE);
        tvTopStatus.setText("已完成");
        llRecord.setEnabled(false);
        llPhoto.setEnabled(false);
        llRecordFile.setEnabled(false);
        llPhotoFile.setEnabled(false);
        setCenterTitle("外访详情", "#FFFFFF");
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        if (EmptyUtils.isNotEmpty(dto) && EmptyUtils.isNotEmpty(dto.getStatus())) {
            getHavedVisitData();
        }
        //重新这是view的magrin
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(llParent.getLayoutParams());
        lp.setMargins(0, 0, 0, 0);
        llParent.setLayoutParams(lp);
    }

    /**
     * 初始化已外访UI
     */
    private void initHavedVisitView() {
        setrightImage(R.drawable.image_to_main, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CcsApplication.clearAllActivitys();
                startActivity(new Intent(BoundDetailActivity.this, MainActivity.class));
            }
        });
        tvRecording.setTextColor(Color.parseColor("#FD887D"));
        tvPhoto.setTextColor(Color.parseColor("#FD887D"));
        ivPhoto.setImageResource(R.drawable.image_photo_noable);
        ivRecord.setImageResource(R.drawable.image_record_noable);
        rlBtnVisit.setVisibility(View.GONE);
        rlBtnDetail.setVisibility(View.VISIBLE);
        setrightTitle("", "#FFFFFF", null);
//        ivCall.setVisibility(View.GONE);
        setCenterTitle("外访详情", "#FFFFFF");
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        srlVisitDetail.setVisibility(View.VISIBLE);
        srlToVisit.setVisibility(View.GONE);
        rlBtnDetail.setVisibility(View.VISIBLE);
        tvTopStatus.setText("已外访");
        llRecord.setEnabled(false);
        llPhoto.setEnabled(false);
        btnDetailOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到数据上传界面
                toUpLoadFileActivity(visitCaseDto.getDto().getStatus(), 0);
            }
        });
        if (EmptyUtils.isNotEmpty(dto) && EmptyUtils.isNotEmpty(dto.getStatus())) {
            getHavedVisitData();
        }
    }

    /**
     * 跳转到数据上传界面
     *
     * @param status 1 待外访
     *               2 已外访
     * @param status 0 录音 1照片
     */
    private void toUpLoadFileActivity(Integer status, int type) {
        //初始化待上传的录音文件
        initRecordData();
        //初始化待上传的图片文件
        initPhotoData();
        //合并文件
        List<File> fileList = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(recordFiles)) {
            fileList.addAll(recordFiles);
        }
        if (EmptyUtils.isNotEmpty(photoFiles)) {
            fileList.addAll(photoFiles);
        }
        boundTaskListViewModel.initFiles(fileList);
        if (EmptyUtils.isNotEmpty(boundTaskListViewModel.getShowVisitUserDtoList(visitCaseDto.getDto().getId()))) {
            EventBus.getDefault().postSticky(boundTaskListViewModel.getShowVisitUserDtoList(visitCaseDto.getDto().getId()));
            if (isStart) {
                ToastUtils.showToast("请结束录音再进行操作");
                return;
            }
            Intent intent = new Intent(BoundDetailActivity.this, UploadSingleUserActivity.class);
            intent.putExtra("status", status);
            intent.putExtra("type", type);
            startActivityForResult(intent, 1001);
        } else {
            showNoFileDiaLog();
        }
    }


    /**
     * 初始化待外访的ui视图
     */
    private void initWaiteVisitView(int code) {
        tvRecording.setTextColor(Color.parseColor("#FD887D"));
        tvPhoto.setTextColor(Color.parseColor("#FD887D"));
        ivPhoto.setImageResource(R.drawable.image_photo_able);
        ivRecord.setImageResource(R.drawable.image_record_able);
        //
        rlBtnVisit.setVisibility(View.VISIBLE);
        rlBtnDetail.setVisibility(View.GONE);
        setCenterTitle("外访记录", "#FFFFFF");
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        setrightTitle("强制退出", "#FFFFFF", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                CcsApplication.clearAllActivitys();
                System.exit(0);
            }
        });
        srlVisitDetail.setVisibility(View.GONE);
        srlToVisit.setVisibility(View.VISIBLE);
        tvTopStatus.setText("进行中");
        llRecord.setEnabled(true);
        llPhoto.setEnabled(true);
        btnVisitOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Integer total = (Integer.parseInt(tvPhoto.getText().toString()) + Integer.parseInt(tvRecording.getText().toString()));
                    if (total <= 0) {
                        showNoFileDiaLog();
                        return;
                    }
                } catch (Exception e) {
                    showNoFileDiaLog();
                    return;
                }
                saveVisitRecord(1);
            }
        });

        btnVisitSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveVisitRecord(null);
            }
        });
        etVisitAddress.setText(dto.getAddress());
        etAddressType.setText(dto.getAddressType());
        //从上传界面回来不要刷新数据
        if (code != 1001 && EmptyUtils.isNotEmpty(dto) && EmptyUtils.isNotEmpty(dto.getStatus())) {
            getWaiteVisitData();
        }

    }

    /**
     * 上传附件
     */
    private void uploadFile() {

    }

    /**
     *
     */
    private void showNoFileDiaLog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_no_file_tips)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        TextView tvOk = (TextView) holder.getView(R.id.tv_ok);
                        tvOk.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                    }
                })
                .show(getSupportFragmentManager());
    }

    /**
     * 获取待外访的数据
     */
    private void getWaiteVisitData() {

        //db获取
        Flowable<SaveVisitRecordBean> flowable = AppDataBase.getInstance(this).getVisitRecord().findVisitRecord(visitCaseDto.getDto().getId());

        flowable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<SaveVisitRecordBean>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(1);
                    }

                    @Override
                    public void onNext(SaveVisitRecordBean saveVisitRecordBean) {

                        String json = JSONObject.toJSONString(saveVisitRecordBean);

                        VisitRecordDetailDto visitRecordDetailDto = JSONObject.parseObject(json, VisitRecordDetailDto.class);

                        initSaveWaiteVisitView(visitRecordDetailDto);

                    }

                    @Override
                    public void onError(Throwable t) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    /**
     * 获取已经外访数据
     */
    private void getHavedVisitData() {

        //db获取
        Flowable<SaveVisitRecordBean> flowable = AppDataBase.getInstance(this).getVisitRecord().findVisitRecord(visitCaseDto.getDto().getId());

        flowable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<SaveVisitRecordBean>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(1);
                    }

                    @Override
                    public void onNext(SaveVisitRecordBean saveVisitRecordBean) {

                        String json = JSONObject.toJSONString(saveVisitRecordBean);

                        VisitRecordDetailDto visitRecordDetailDto = JSONObject.parseObject(json, VisitRecordDetailDto.class);

                        if (visitRecordDetailDto.getEndTime() != null) {
                            visitRecordDetailDto.setEndTimeStr(visitRecordDetailDto.getEndTime());
                        }
                        visitRecordDetailDto.setVisitAddress(saveVisitRecordBean.getVisitEndAddress()==null?saveVisitRecordBean.getVisitAddress():saveVisitRecordBean.getVisitEndAddress());
                        initRecordDetaiView(visitRecordDetailDto);

                    }

                    @Override
                    public void onError(Throwable t) {
                        Log.e(TAG, "onError: " + t);
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    private Long id;//详情id
    private String customAdress = "";
    private String customStreet = "";

    /**
     * 回显示
     *
     * @param data
     */
    private void initSaveWaiteVisitView(VisitRecordDetailDto data) {
        this.id = data.getId();
        //外访时间
        etVisitTime.setText(data.getVisitTimeStr());
        //协助专员
        etAssistCommissioner.setText(data.getAssistCommissioner());
        // 判断是 默认地址还是自定义，1默认，2自定义
        //外访地址
        if (EmptyUtils.isNotEmpty(data.getType())) {
            //默认
            if (data.getType() == 1) {
                isDefaut = true;
                tvCustom.setBackgroundResource(R.drawable.shape_input_to_visit);
                tvDefault.setBackgroundResource(R.drawable.shape_button_select_bg);
                tvCustom.setTextColor(Color.parseColor("#999999"));
                tvDefault.setTextColor(Color.parseColor("#FFFFFF"));
                etVisitAddress.setText(dto.getAddress());
                etAddressType.setText(dto.getAddressType());
                rlStreetAddress.setVisibility(View.GONE);
                etVisitAddress.setEnabled(false);
                etAddressType.setEnabled(false);
            }
            //自定义
            else if (data.getType() == 2) {
                isDefaut = false;
                tvCustom.setBackgroundResource(R.drawable.shape_button_select_bg);
                tvDefault.setBackgroundResource(R.drawable.shape_input_to_visit);
                tvCustom.setTextColor(Color.parseColor("#FFFFFF"));
                tvDefault.setTextColor(Color.parseColor("#999999"));
                if (EmptyUtils.isNotEmpty(data.getVisitAddress()) && data.getVisitAddress().contains("-")) {
                    String adresses[] = data.getVisitAddress().split("-");
                    if (adresses.length == 1) {
                        customAdress = adresses[0];
                        etVisitAddress.setText(customAdress);
                    } else if (adresses.length == 2) {
                        customAdress = adresses[0];
                        etVisitAddress.setText(customAdress);
                        customStreet = adresses[1];
                        etStreetAddres.setText(customStreet);
                    }

                }
//              //地址类型
                etAddressType.setText(data.getAddressType());
                rlStreetAddress.setVisibility(View.VISIBLE);
                etVisitAddress.setEnabled(true);
                etAddressType.setEnabled(true);

            }
        }
        //外访情况
        if (data.getVisitSituation() != null && data.getVisitSituation() >= 0 && data.getVisitSituation() < visitSituationList.size()) {
            etVisitSituation.setText(visitSituationList.get(data.getVisitSituation()));
        }
        //新联系方式
        etNewContact.setText(data.getNewContact());
        //新联系地址
        etNewAddress.setText(data.getNewAddress());
        //外访描述
        etCasedevelopment.setText(data.getCaseDevelopment());
        //邻居描述
        etDescription.setText(data.getDescription());
        //交通工具
        etVehicle.setText(data.getVehicle());
        //交通费用
        etVehiclefee.setText(data.getVehicleFee() == null ? "" : NumberUtils.twoDecimalPlaces(data.getVehicleFee()));
        //下一步描述
        etNextStep.setText(data.getNextStep());
        //邻居是否认识持卡人
        if (EmptyUtils.isNotEmpty(data.getIsKown())) {
            //知道
            if (data.getIsKown() == 1) {
                ivNoYes.setImageResource(R.drawable.image_yes);
                etDescription.setVisibility(View.VISIBLE);
                isKnow = true;
            }
            //不知道
            else if (data.getIsKown() == 0) {
                ivNoYes.setImageResource(R.drawable.image_no);
                etDescription.setVisibility(View.GONE);
                isKnow = false;
            }
        }
        //外访房屋
        Integer visitHouse = data.getVisitHouse();
        if (EmptyUtils.isNotEmpty(visitHouse) && visitHouse > 0) {
            visithouseDtoList.get(visitHouse - 1).setSelect(true);
            vsitHouseAdapter.notifyDataSetChanged();
        }

        //家用电器
        String houseAppliance = data.getHouseAppliance();
        if (EmptyUtils.isNotEmpty(houseAppliance)) {
            if (houseAppliance.contains(",")) {
                String[] strs = houseAppliance.split(",");
                for (int i = 0; i < strs.length; i++) {
                    if ((Integer.parseInt(strs[i]) - 1) >= 0) {
                        houseapplianceList.get(Integer.parseInt(strs[i]) - 1).setSelect(true);
                    }

                }
            } else {
                if ((Integer.parseInt(houseAppliance) - 1) >= 0) {
                    houseapplianceList.get(Integer.parseInt(houseAppliance) - 1).setSelect(true);
                }

            }
        }
        houseapplianceAdapter.notifyDataSetChanged();

        //信箱情况
        String emailSituation = data.getEmailSituation();
        if (EmptyUtils.isNotEmpty(emailSituation)) {
            if (emailSituation.contains(",")) {
                String[] strs = emailSituation.split(",");
                for (int i = 0; i < strs.length; i++) {
                    if ((Integer.parseInt(strs[i]) - 1) >= 0) {
                        emailsituationsList.get(Integer.parseInt(strs[i]) - 1).setSelect(true);
                    }

                }
            } else {
                if ((Integer.parseInt(emailSituation) - 1) >= 0) {
                    emailsituationsList.get(Integer.parseInt(emailSituation) - 1).setSelect(true);
                }

            }
        }
        emailsituationsAdapter.notifyDataSetChanged();

        //室内装修
        Integer innerDecoration = data.getInnerDecoration();
        if (EmptyUtils.isNotEmpty(innerDecoration) && innerDecoration > 0) {
            innerDecorationList.get(innerDecoration - 1).setSelect(true);
            innerdecorationseAdapter.notifyDataSetChanged();
        }
        //居住情况
        Integer livingSituation = data.getLivingSituation();
        if (EmptyUtils.isNotEmpty(livingSituation) && livingSituation > 0) {
            livingsituationsList.get(livingSituation - 1).setSelect(true);
            livingsituationsAdapter.notifyDataSetChanged();
        }
        //房屋面积
        Integer houseArea = data.getHouseArea();
        if (EmptyUtils.isNotEmpty(houseArea) && houseArea > 0) {
            visithousesSizeList.get(houseArea - 1).setSelect(true);
            visithousesSizeAdapter.notifyDataSetChanged();
        }
        //还款能力
        Integer repayPower = data.getRepayPower();
        if (EmptyUtils.isNotEmpty(repayPower) && repayPower > 0) {
            repaypowersList.get(repayPower - 1).setSelect(true);
            repaypowersAdapter.notifyDataSetChanged();
        }

    }


    //外访房屋
    private String[] visitHouses = new String[]{"未知", "小区私人住宅", "非小区住宅", "公司宿舍", "农民房出租", "公司住宅", "写字楼", "工厂", "店铺", "其他"};
    //室内装修
    private String[] innerDecorations = new String[]{"未知", "新", "旧", "豪华", "普通", "简朴"};
    //家用电器
    private String[] houseAppliances = new String[]{"未知", "全自动洗衣机", "29存以上电视", "电脑", "电话", "空调 ", "冰箱", "其他"};
    //居住情况
    private String[] livingSituations = new String[]{"未知", "与父母同居", "与配偶同住", "与父母和配偶同居", "独住"};
    //还款能力
    private String[] repayPowers = new String[]{"未知", "有还款能力", "有部分还款能力", "无法判断", "无还款能力"};
    //信箱情况
    private String[] emailSituations = new String[]{"未知", "有水电费单", "有大量信件", "少量信件", "无水电费单", "无信件", "密封信箱", "无信箱"};
    //信箱情况
    private String emailSituationStr = "";
    //家用电器
    private String houseApplianceStr = "";

    /**
     * 展示外访详情
     *
     * @param data
     */
    private void initRecordDetaiView(VisitRecordDetailDto data) {
        try {
            if (EmptyUtils.isNotEmpty(data.getFileMap()) && visitCaseDto.getDto().getStatus() == 3) {
                tvRecording.setText(data.getFileMap().get("record") + "");
                tvPhoto.setText(data.getFileMap().get("photo") + "");
            }
            //外访时间
            tvVisitTime.setText(data.getVisitTimeStr());

            //结束时间
            tvStopTme.setText( data.getEndTimeStr());


            //协助专员
            tvHelper.setText( data.getAssistCommissioner());



            //地址类型
            tvAdressType.setText( data.getAddressType());



            //外访地址
            tvVisitAddress.setText(data.getVisitAddress());



            //外访情况
            if (data.getVisitSituation() != null && data.getVisitSituation() >= 0 && data.getVisitSituation() < visitSituationList.size()) {
                tvVisitStatus.setText(visitSituationList.get(data.getVisitSituation()));
            }

            //新联系方式
            tvNewPhone.setText( data.getNewContact());



            //新联系地址
//            tvNewAddress.setText("????????????????????????");
            tvNewAddress.setText( data.getNewAddress());



            //外访描述
            tvVisitContent.setText( data.getCaseDevelopment());


            //外访房屋
            if (EmptyUtils.isNotEmpty(data.getVisitHouse())) {
                tvVisitHouse.setText(visitHouses[data.getVisitHouse()]);
            }
            //室内装修
            if (EmptyUtils.isNotEmpty(data.getInnerDecoration())) {
                tvDecorate.setText(innerDecorations[data.getInnerDecoration()]);
            }
            houseApplianceStr = "";
            //家用电器
            if (EmptyUtils.isNotEmpty(data.getHouseAppliance())) {
                if (data.getHouseAppliance().contains(",")) {
                    String strs[] = data.getHouseAppliance().split(",");
                    for (int i = 0; i < strs.length; i++) {
                        int ints = Integer.parseInt(strs[i]);
                        if (i != strs.length - 1) {
                            houseApplianceStr = houseApplianceStr + houseAppliances[ints] + ",";
                        } else {
                            houseApplianceStr = houseApplianceStr + houseAppliances[ints] + "";
                        }
                    }
                } else {
                    houseApplianceStr = houseAppliances[Integer.parseInt(data.getHouseAppliance())];
                }

            }
            tvHomeAppliance.setText(houseApplianceStr);



            //居住情况
            if (EmptyUtils.isNotEmpty(data.getLivingSituation())) {
                tvLivingSituation.setText(livingSituations[data.getLivingSituation()]);
            }
            emailSituationStr = "";
            //邮箱情况
            if (EmptyUtils.isNotEmpty(data.getEmailSituation())) {
                if (data.getEmailSituation().contains(",")) {
                    String strs[] = data.getEmailSituation().split(",");
                    for (int i = 0; i < strs.length; i++) {
                        int ints = Integer.parseInt(strs[i]);
                        if (i != strs.length - 1) {
                            emailSituationStr = emailSituationStr + emailSituations[ints] + ",";
                        } else {
                            emailSituationStr = emailSituationStr + emailSituations[ints] + "";
                        }
                    }
                } else {
                    emailSituationStr = emailSituations[Integer.parseInt(data.getEmailSituation())];
                }

            }
            tvEmailSituation.setText( emailSituationStr);
            if (TextUtils.isEmpty(emailSituationStr)) {
                tvEmailSituation.setTextColor(Color.parseColor("#888888"));
            }

            //还款能力
            if (EmptyUtils.isNotEmpty(data.getRepayPower())) {
                tvReimbursementAbility.setText(repayPowers[data.getRepayPower()]);
            }
            //是否认识持卡人
            if (data.getIsKown() != null && data.getIsKown() == 1) {
                rlDescription.setVisibility(View.VISIBLE);
                //邻居描述
                tvNeighborsDescribed.setText( data.getDescription());

                if (TextUtils.isEmpty(data.getNextStep())) {
                    tvNeighborsDescribed.setTextColor(Color.parseColor("#888888"));
                }


                tvIsSee.setText("是");
            } else {
                rlDescription.setVisibility(View.GONE);
                tvIsSee.setText("否");
            }
            //下一步措施
            tvNextStep.setText(data.getNextStep());

        } catch (Exception e) {
        }

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        EventBus.getDefault().register(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.getInstance().mLocationClient.stop();
        CcsApplication.getInstance().mLocationClient.unRegisterLocationListener(this);
        CcsApplication.removeActivity(this);
        EventBus.getDefault().unregister(this);
    }

    /**
     * 是否是打电话导致停止录音的
     */
    private boolean isCallStop;


    @Override
    protected void createViewModel() {
        photoViewModel = ViewModelProviders.of(this).get(PhotoViewModel.class);
        boundTaskListViewModel = ViewModelProviders.of(this).get(BoundTaskListViewModel.class);
        recordViewModel = ViewModelProviders.of(this).get(RecordViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_bounddetail;
    }

    private LinearLayout llRecordFile;
    private LinearLayout llPhotoFile;

    private TakePhoto takePhoto;

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        Log.e(TAG, "takeSuccess: " + result.getImage().getOriginalPath());
        //把文件数据写到内存卡

        File file = new File(Environment.getExternalStorageDirectory() + "/temp/" + getFileName() + ".txt");

        //获取json字符串
        VisitUserDto visitUserDto = getVisitUserDto("2", getFileName());

        //设置文件地址
        visitUserDto.setFilePath(Environment.getExternalStorageDirectory() + "/temp/" + getFileName() + ".jpg");
        //设置文本地址
        visitUserDto.setTxtFilePath(Environment.getExternalStorageDirectory() + "/temp/" + getFileName() + ".txt");
        ToastUtils.showToast("正在保存文件");
        new Thread() {
            @Override
            public void run() {
                super.run();
                FileUtil.writeJsonToFile(file, JSONObject.toJSONString(visitUserDto));
                handler.sendEmptyMessage(800);
            }
        }.start();


    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void initView() {
        ///
        parentView = getWindow().getDecorView();
        tvIsSee = (TextView) findViewById(R.id.tv_is_see);
        rlDescription = (RelativeLayout) findViewById(R.id.rl_description);
        tvNextStep = (TextView) findViewById(R.id.tv_next_step);
        srlToVisit = (SmartRefreshLayout) findViewById(R.id.srl_to_visit);
        srlVisitDetail = (SmartRefreshLayout) findViewById(R.id.srl_visit_detail);
        //禁止上拉加载
        srlToVisit.setEnableLoadMore(false);
        //禁止下拉刷新
        srlToVisit.setEnableRefresh(false);
        //禁止上拉加载
        srlVisitDetail.setEnableLoadMore(false);
        // //禁止下拉刷新
        srlVisitDetail.setEnableRefresh(false);
        tvRelationShip = (TextView) findViewById(R.id.tv_relation_ship);
        btnVisitSave = (Button) findViewById(R.id.btn_visit_save);
        tvRecording = (TextView) findViewById(R.id.tv_recording);
        tvPhoto = (TextView) findViewById(R.id.tv_photo);
        llRecord = (LinearLayout) findViewById(R.id.ll_record);
        llPhoto = (LinearLayout) findViewById(R.id.ll_photo);
        tvTopName = (TextView) findViewById(R.id.tv_top_name);
        tvTopStatus = (TextView) findViewById(R.id.tv_top_status);
        tvTopAccount = (TextView) findViewById(R.id.tv_top_account);
        ivRecord = (ImageView) findViewById(R.id.iv_record);
        ivPhoto = (ImageView) findViewById(R.id.iv_photo);
        tvVisitTime = (TextView) findViewById(R.id.tv_visit_time);
        tvStopTme = (TextView) findViewById(R.id.tv_stop_tme);
        tvHelper = (TextView) findViewById(R.id.tv_helper);
        tvAdressType = (TextView) findViewById(R.id.tv_adress_type);
        tvVisitAddress = (TextView) findViewById(R.id.tv_visit_address);
        tvVisitStatus = (TextView) findViewById(R.id.tv_visit_status);
        tvNewPhone = (TextView) findViewById(R.id.tv_new_phone);
        tvNewAddress = (TextView) findViewById(R.id.tv_new_address);
        tvVisitContent = (TextView) findViewById(R.id.tv_visit_content);
        tvVisitHouse = (TextView) findViewById(R.id.tv_visit_house);
        tvDecorate = (TextView) findViewById(R.id.tv_decorate);
        tvHomeAppliance = (TextView) findViewById(R.id.tv_home_appliance);
        tvLivingSituation = (TextView) findViewById(R.id.tv_living_situation);
        tvEmailSituation = (TextView) findViewById(R.id.tv_email_situation);
        tvReimbursementAbility = (TextView) findViewById(R.id.tv_reimbursement_ability);
        tvNeighborsDescribed = (TextView) findViewById(R.id.tv_neighbors_described);
//        childVisitDeatil = (CustomerScrollView) findViewById(R.id.child_visit_deatil);
//        childToVisit = (CustomerScrollView) findViewById(R.id.child_to_visit);
        rlVisitAddress = (RelativeLayout) findViewById(R.id.rl_visit_address);
        etVisitAddress = (EditText) findViewById(R.id.et_visit_address);
        tvDefault = (TextView) findViewById(R.id.tv_default);
        tvCustom = (TextView) findViewById(R.id.tv_custom);
        rlStreetAddress = (RelativeLayout) findViewById(R.id.rl_street_address);
        rlBtnDetail = (RelativeLayout) findViewById(R.id.rl_btn_detail);
        rlBtnVisit = (LinearLayout) findViewById(R.id.rl_btn_visit);
        btnVisitOk = (Button) findViewById(R.id.btn_visit_ok);
        btnDetailOk = (Button) findViewById(R.id.btn_detail_ok);
        rvVisithouses = (RecyclerView) findViewById(R.id.rv_visithouses);
        rvInnerdecorations = (RecyclerView) findViewById(R.id.rv_innerdecorations);
        rvHouseappliances = (RecyclerView) findViewById(R.id.rv_houseappliances);
        rvLivingsituations = (RecyclerView) findViewById(R.id.rv_livingsituations);
        rvVisithousesSize = (RecyclerView) findViewById(R.id.rv_visithouses_size);
        rvEmailsituations = (RecyclerView) findViewById(R.id.rv_emailsituations);
        rvRepaypowers = (RecyclerView) findViewById(R.id.rv_repaypowers);
        etVisitTime = (EditText) findViewById(R.id.et_visit_time);
        ivNoYes = (ImageView) findViewById(R.id.iv_no_yes);
        etAssistCommissioner = (EditText) findViewById(R.id.et_assist_commissioner);
        etAddressType = (EditText) findViewById(R.id.et_address_type);
        etVisitSituation = (EditText) findViewById(R.id.et_visit_situation);
        etVehicle = (EditText) findViewById(R.id.et_vehicle);
        rvAssistcommissioner = (RecyclerView) findViewById(R.id.rv_assistcommissioner);
        etVehiclefee = (EditText) findViewById(R.id.et_vehiclefee);
        linearLayoutManager = new LinearLayoutManager(this);
        rvAssistcommissioner.setLayoutManager(linearLayoutManager);
        etNewContact = (EditText) findViewById(R.id.et_new_contact);
        etNewAddress = (EditText) findViewById(R.id.et_new_address);
        etCasedevelopment = (EditText) findViewById(R.id.et_casedevelopment);
        etDescription = (EditText) findViewById(R.id.et_description);
        etNextStep = (EditText) findViewById(R.id.et_nextStep);
        rlVisithouses = (RelativeLayout) findViewById(R.id.rl_visithouses);
        rlInnerdecorations = (RelativeLayout) findViewById(R.id.rl_innerdecorations);
        rlHouseappliances = (RelativeLayout) findViewById(R.id.rl_houseappliances);
        rlLivingsituations = (RelativeLayout) findViewById(R.id.rl_livingsituations);
        rlEmailsituations = (RelativeLayout) findViewById(R.id.rl_emailsituations);
        rlRepaypowers = (RelativeLayout) findViewById(R.id.rl_repaypowers);
        etStreetAddres = (EditText) findViewById(R.id.et_street_addres);
        rlBtnVisit = (LinearLayout) findViewById(R.id.rl_btn_visit);
        rlBtnDetail = (RelativeLayout) findViewById(R.id.rl_btn_detail);
        llParent = (LinearLayout) findViewById(R.id.ll_parent);
        llRecordFile = (LinearLayout) findViewById(R.id.ll_record_file);
        llPhotoFile = (LinearLayout) findViewById(R.id.ll_photo_file);
        visitCaseDto = (VisitCaseDto) getIntent().getSerializableExtra("visitCaseDto");
        initCase(visitCaseDto);
        ivRecord.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(View oldFocus, View newFocus) {
                initGuide();
            }
        });
        conn = new MyConnection();
        intentService = new Intent(BoundDetailActivity.this, RecordServcie.class);


    }

    private Intent intentService = null;
    private MyConnection conn = null;


    /**
     * 初始化引导页
     */
    private void initGuide() {
        if (!SPUtil.getData(Constant.SP.SHOW_GUIDE_SP, Constant.SP.SHOW_GUIDE, Boolean.class, false)) {
            SPUtil.putData(Constant.SP.SHOW_GUIDE_SP, Constant.SP.SHOW_GUIDE, true);
            showGuideOne();
        }
    }

    /**
     * 弹出引导 1
     */
    private void showGuideOne() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_guide_one, (ViewGroup) getWindow().getDecorView(), false);
        ImageView ivSkip = (ImageView) view.findViewById(R.id.iv_skip);
        TextView tvOk = (TextView) view.findViewById(R.id.tv_ok);
        final GuideViewHelper guideViewHelper = new GuideViewHelper(this);
        guideViewHelper.addView(llRecordFile, new CustomerLayoutStyle(view))
                .type(LightType.Circle)
                .onDismiss(new GuideView.OnDismissListener() {
                    @Override
                    public void dismiss() {

                    }
                })
                .show();
        ivSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guideViewHelper.nextLight();

            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guideViewHelper.nextLight();
                showGuideTwo();
            }
        });

    }

    /**
     * 弹出引导 2
     */
    private void showGuideTwo() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_guide_two, (ViewGroup) getWindow().getDecorView(), false);
        ImageView ivSkip = (ImageView) view.findViewById(R.id.iv_skip);
        TextView tvOk = (TextView) view.findViewById(R.id.tv_ok);
        final GuideViewHelper guideViewHelper = new GuideViewHelper(this);
        guideViewHelper.addView(llRecord, new CustomerLayoutStyle(view))
                .type(LightType.Circle)
                .onDismiss(new GuideView.OnDismissListener() {
                    @Override
                    public void dismiss() {

                    }
                })
                .show();
        ivSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guideViewHelper.nextLight();

            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guideViewHelper.nextLight();
                showGuideThree();
            }
        });

    }

    /**
     * 弹出引导 3
     */
    private void showGuideThree() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_guide_three, (ViewGroup) getWindow().getDecorView(), false);
        ImageView ivSkip = (ImageView) view.findViewById(R.id.iv_skip);
        TextView tvOk = (TextView) view.findViewById(R.id.tv_ok);
        final GuideViewHelper guideViewHelper = new GuideViewHelper(this);
        guideViewHelper.addView(llPhotoFile, new CustomerLayoutStyle(view))
                .type(LightType.Circle)
                .onDismiss(new GuideView.OnDismissListener() {
                    @Override
                    public void dismiss() {

                    }
                })
                .show();
        ivSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guideViewHelper.nextLight();

            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guideViewHelper.nextLight();
                showGuideFour();
            }
        });
    }

    /**
     * 弹出引导 4
     */
    private void showGuideFour() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_guide_four, (ViewGroup) getWindow().getDecorView(), false);
        ImageView ivSkip = (ImageView) view.findViewById(R.id.iv_skip);
        TextView tvOk = (TextView) view.findViewById(R.id.tv_ok);
        final GuideViewHelper guideViewHelper = new GuideViewHelper(this);
        guideViewHelper.addView(llPhoto, new CustomerLayoutStyle(view))
                .type(LightType.Circle)
                .onDismiss(new GuideView.OnDismissListener() {
                    @Override
                    public void dismiss() {

                    }
                })
                .show();
        ivSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guideViewHelper.nextLight();
            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guideViewHelper.nextLight();
                showGuideFive();
            }
        });
    }

    /**
     * 弹出引导 5
     */
    private void showGuideFive() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_guide_five, (ViewGroup) getWindow().getDecorView(), false);
        ImageView ivSkip = (ImageView) view.findViewById(R.id.iv_skip);
        TextView tvOk = (TextView) view.findViewById(R.id.tv_ok);
        final GuideViewHelper guideViewHelper = new GuideViewHelper(this);
        guideViewHelper.padding(DisplayUtil.dip2px(this, 10));
        ivSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guideViewHelper.nextLight();
            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guideViewHelper.nextLight();
            }
        });
    }

    //房屋情况
    private RecyclerView rvVisithouses;
    private FlexboxLayoutManager fm_Visithouse;
    //室内装修
    private RecyclerView rvInnerdecorations;
    private FlexboxLayoutManager fm_Innerdecorationse;
    //家用电器
    private RecyclerView rvHouseappliances;
    private FlexboxLayoutManager fm_Houseappliances;
    //居住情况
    private RecyclerView rvLivingsituations;
    private FlexboxLayoutManager fm_Livingsituations;
    //房屋面积
    private RecyclerView rvVisithousesSize;
    private FlexboxLayoutManager fm_VisithousesSize;
    //信箱情况
    private RecyclerView rvEmailsituations;
    private FlexboxLayoutManager fm_Emailsituations;
    //还款能力
    private RecyclerView rvRepaypowers;
    private FlexboxLayoutManager fm_Repaypowers;
    //协助专员
    private EditText etAssistCommissioner;
    //地址类型
    private EditText etAddressType;
    //外访情况
    private EditText etVisitSituation;
    //交通工具
    private EditText etVehicle;
    //选择外访专员
    private RecyclerView rvAssistcommissioner;
    private LinearLayoutManager linearLayoutManager;
    private EditText etVehiclefee;
    private EditText etNewContact;
    private EditText etNewAddress;
    private EditText etCasedevelopment;
    private EditText etDescription;
    private EditText etNextStep;
    private String beginTime;//开始外访时间

    @Override
    public void initData() {

        //初始化外访房屋
        initOutboundHousesListView();
        //初始化室内装修
        initInnerdecorationseListView();
        //初始化家用电器
        initHouseappliances();
        //初始化居住情况
        initLivingsituations();
        //初始化房屋面积
//        initVisithousesSize();
        //初始化信箱情况
        initEmailsituations();
        //初始化还款能力
        initRepaypowers();
        //初始化外访情况
        initVisitSituationList();
        beginTime = DateUtil.coverDateFormat("yyyy-MM-dd HH:mm:ss", new Date());


    }

    @Override
    protected void onStart() {
        super.onStart();
        //打开位置设置界面
        getLocationSetting();
        //获取定位权限以及录音，拍照，写文件权限
        initPermission();
    }

    /**
     * 打开位置设置
     */
    private void getLocationSetting() {
        if (!NetworkUtil.isGpsOPen(this)) {
            //  CcsApplication.getInstance().mLocationClient.stop();
            //位置信息没有开启
            DialogUtils.showAdressInfoDailog("无法获取当前位置信息，请在手机设置中开启位置信息", BoundDetailActivity.this);
            //Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            //startActivity(in  tent);

            return;
        }
    }

    List<String> visitSituationList;

    /**
     * //初始化外访情况
     */
    private void initVisitSituationList() {
        visitSituationList = new ArrayList<>();
        //顺序不能乱
        visitSituationList.add("本人在家");
        visitSituationList.add("家人在家");
        visitSituationList.add("家中无人");
        visitSituationList.add("非本人住址");
        visitSituationList.add("本人在公司");
        visitSituationList.add("本人不在公司");
        visitSituationList.add("非本人公司");
        visitSituationList.add("无效地址");
    }


    private List<VisithouseDto> repaypowersList;
    private RepaypowersAdapter repaypowersAdapter;

    //初始化还款能力
    private void initRepaypowers() {
        repaypowersList = new ArrayList<>();
        repaypowersList.add(new VisithouseDto(false, "有还款能力", 1));
        repaypowersList.add(new VisithouseDto(false, "有部分还款能力", 2));
        repaypowersList.add(new VisithouseDto(false, "无法判断", 3));
        repaypowersList.add(new VisithouseDto(false, "无还款能力", 4));
        fm_Repaypowers = new FlexboxLayoutManager(this);
        //设置主轴排列方式
        fm_Repaypowers.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        fm_Repaypowers.setFlexWrap(FlexWrap.WRAP);
        fm_Repaypowers.setAlignItems(AlignItems.STRETCH);
        rvRepaypowers.setLayoutManager(fm_Repaypowers);
        repaypowersAdapter = new RepaypowersAdapter(this, repaypowersList, this);
        rvRepaypowers.setAdapter(repaypowersAdapter);
    }

    private List<VisithouseDto> emailsituationsList;
    private EmailsituationsAdapter emailsituationsAdapter;

    //初始化信箱情况
    private void initEmailsituations() {
        emailsituationsList = new ArrayList<>();
        emailsituationsList.add(new VisithouseDto(false, "有水电费单", 1));
        emailsituationsList.add(new VisithouseDto(false, "有大量信件", 2));
        emailsituationsList.add(new VisithouseDto(false, "少量信件", 3));
        emailsituationsList.add(new VisithouseDto(false, "无水电费", 4));
        emailsituationsList.add(new VisithouseDto(false, "无信件", 5));
        emailsituationsList.add(new VisithouseDto(false, "密封信箱", 6));
        emailsituationsList.add(new VisithouseDto(false, "无信箱", 7));
        fm_Emailsituations = new FlexboxLayoutManager(this);
        //设置主轴排列方式
        fm_Emailsituations.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        fm_Emailsituations.setFlexWrap(FlexWrap.WRAP);
        fm_Emailsituations.setAlignItems(AlignItems.STRETCH);
        rvEmailsituations.setLayoutManager(fm_Emailsituations);
        emailsituationsAdapter = new EmailsituationsAdapter(this, emailsituationsList, this);
        rvEmailsituations.setAdapter(emailsituationsAdapter);
    }

    // private String[] buildingAreas = new String[]{"<60平", "60-100平", "100-140平", "140平以上"};
    private List<VisithouseDto> visithousesSizeList;
    private VisithousesSizeAdapter visithousesSizeAdapter;

    //初始化房屋面积
    private void initVisithousesSize() {
        visithousesSizeList = new ArrayList<>();
        visithousesSizeList.add(new VisithouseDto(false, "<60平", 1));
        visithousesSizeList.add(new VisithouseDto(false, "60-100平", 2));
        visithousesSizeList.add(new VisithouseDto(false, "100-140平", 3));
        visithousesSizeList.add(new VisithouseDto(false, "140平以上", 4));
        fm_VisithousesSize = new FlexboxLayoutManager(this);
        //设置主轴排列方式
        fm_VisithousesSize.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        fm_VisithousesSize.setFlexWrap(FlexWrap.WRAP);
        fm_VisithousesSize.setAlignItems(AlignItems.STRETCH);
        rvVisithousesSize.setLayoutManager(fm_VisithousesSize);
        visithousesSizeAdapter = new VisithousesSizeAdapter(this, visithousesSizeList, this);
        rvVisithousesSize.setAdapter(visithousesSizeAdapter);
    }

    private List<VisithouseDto> livingsituationsList;
    private LivingsituationsAdapter livingsituationsAdapter;

    //初始化居住情况
    private void initLivingsituations() {
        livingsituationsList = new ArrayList<>();
        livingsituationsList.add(new VisithouseDto(false, "与父母同居", 1));
        livingsituationsList.add(new VisithouseDto(false, "与配偶同住", 2));
        livingsituationsList.add(new VisithouseDto(false, "与父母和配偶同居", 3));
        livingsituationsList.add(new VisithouseDto(false, "独住", 4));
        fm_Livingsituations = new FlexboxLayoutManager(this);
        //设置主轴排列方式
        fm_Livingsituations.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        fm_Livingsituations.setFlexWrap(FlexWrap.WRAP);
        fm_Livingsituations.setAlignItems(AlignItems.STRETCH);
        rvLivingsituations.setLayoutManager(fm_Livingsituations);
        livingsituationsAdapter = new LivingsituationsAdapter(this, livingsituationsList, this);
        rvLivingsituations.setAdapter(livingsituationsAdapter);
    }

    //初始化家用电器
    private List<VisithouseDto> houseapplianceList;
    private HouseapplianceAdapter houseapplianceAdapter;

    private void initHouseappliances() {
        houseapplianceList = new ArrayList<>();
        houseapplianceList.add(new VisithouseDto(false, "全自动洗衣机", 1));
        houseapplianceList.add(new VisithouseDto(false, "29存以上电视", 2));
        houseapplianceList.add(new VisithouseDto(false, "电脑", 3));
        houseapplianceList.add(new VisithouseDto(false, "电话", 4));
        houseapplianceList.add(new VisithouseDto(false, "空调", 5));
        houseapplianceList.add(new VisithouseDto(false, "冰箱", 6));
        houseapplianceList.add(new VisithouseDto(false, "其他", 7));

        fm_Houseappliances = new FlexboxLayoutManager(this);
        //设置主轴排列方式
        fm_Houseappliances.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        fm_Houseappliances.setFlexWrap(FlexWrap.WRAP);
        fm_Houseappliances.setAlignItems(AlignItems.STRETCH);
        rvHouseappliances.setLayoutManager(fm_Houseappliances);
        houseapplianceAdapter = new HouseapplianceAdapter(this, houseapplianceList, this);
        rvHouseappliances.setAdapter(houseapplianceAdapter);

    }

    private List<VisithouseDto> innerDecorationList;
    private InnerdecorationseAdapter innerdecorationseAdapter;

    //初始化室内装修
    private void initInnerdecorationseListView() {
        innerDecorationList = new ArrayList<>();
        innerDecorationList.add(new VisithouseDto(false, "新", 1));
        innerDecorationList.add(new VisithouseDto(false, "旧", 2));
        innerDecorationList.add(new VisithouseDto(false, "豪华", 3));
        innerDecorationList.add(new VisithouseDto(false, "普通", 4));
        innerDecorationList.add(new VisithouseDto(false, "简朴", 5));
        fm_Innerdecorationse = new FlexboxLayoutManager(this);
        //设置主轴排列方式
        fm_Innerdecorationse.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        fm_Innerdecorationse.setFlexWrap(FlexWrap.WRAP);
        fm_Innerdecorationse.setAlignItems(AlignItems.STRETCH);
        rvInnerdecorations.setLayoutManager(fm_Innerdecorationse);
        innerdecorationseAdapter = new InnerdecorationseAdapter(this, innerDecorationList, this);
        rvInnerdecorations.setAdapter(innerdecorationseAdapter);

    }

    private List<VisithouseDto> visithouseDtoList;
    private VsitHouseAdapter vsitHouseAdapter;

    //初始化外访房屋列表视图
    private void initOutboundHousesListView() {
        visithouseDtoList = new ArrayList<>();
        visithouseDtoList.add(new VisithouseDto(false, "小区私人住宅", 1));
        visithouseDtoList.add(new VisithouseDto(false, "非小区住宅", 2));
        visithouseDtoList.add(new VisithouseDto(false, "公司宿舍", 3));
        visithouseDtoList.add(new VisithouseDto(false, "农民房出租", 4));
        visithouseDtoList.add(new VisithouseDto(false, "公司住宅", 5));
        visithouseDtoList.add(new VisithouseDto(false, "写字楼", 6));
        visithouseDtoList.add(new VisithouseDto(false, "工厂", 7));
        visithouseDtoList.add(new VisithouseDto(false, "店铺", 8));
        visithouseDtoList.add(new VisithouseDto(false, "其他", 9));
        fm_Visithouse = new FlexboxLayoutManager(this);
        //设置主轴排列方式
        fm_Visithouse.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        fm_Visithouse.setFlexWrap(FlexWrap.WRAP);
        fm_Visithouse.setAlignItems(AlignItems.STRETCH);
        rvVisithouses.setLayoutManager(fm_Visithouse);
        vsitHouseAdapter = new VsitHouseAdapter(this, visithouseDtoList, this);
        rvVisithouses.setAdapter(vsitHouseAdapter);
    }

    /**
     * 获取定位权限以及录音，拍照，写文件权限
     */
    private void initPermission() {
        RxPermissions.getInstance(this).request(
                Manifest.permission.RECORD_AUDIO,//录音权限
                Manifest.permission.ACCESS_COARSE_LOCATION, //定位权限
                Manifest.permission.ACCESS_FINE_LOCATION,//定位权限
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//写权限
                Manifest.permission.READ_EXTERNAL_STORAGE, //读权限
                Manifest.permission.READ_PHONE_STATE,//电话权限
                Manifest.permission.CAMERA//相机权限
        ).subscribe(new PermissionsObserver() {
            @Override
            protected void onGetPermissionsSuccess() {
                //开启定位
                CcsApplication.getInstance().mLocationClient.start();
                CcsApplication.getInstance().mLocationClient.registerLocationListener(BoundDetailActivity.this);
            }

            @Override
            protected void onGetPermissionsSuccessFailuer() {
                if (!PermissionUtils.hasPermission(BoundDetailActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, BoundDetailActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(BoundDetailActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, BoundDetailActivity.this);
                    return;
                }

                if (!PermissionUtils.hasPermission(BoundDetailActivity.this, new String[]{Manifest.permission.CAMERA})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.CAMERA_MESSAGE, BoundDetailActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(BoundDetailActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.EXTERNAL_MESSAGE, BoundDetailActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(BoundDetailActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.EXTERNAL_MESSAGE, BoundDetailActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(BoundDetailActivity.this, new String[]{Manifest.permission.RECORD_AUDIO})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.RECORD_MESSAGE, BoundDetailActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(BoundDetailActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.PHONE_MESSAGE, BoundDetailActivity.this);
                    return;
                }
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isServiceWork(this, "com.mujin.keji.collectionsystem.server.RecordServcie"))
        {
            Log.e(TAG, "onResume---: " + Constant.visitId);
            Log.e(TAG, "onResume+++: " + visitCaseDto.getDto().getId());
            if (Constant.visitId.equals(visitCaseDto.getDto().getId())) {
                //显示录音的状态
                ImageUtils.loadImage(BoundDetailActivity.this, R.drawable.gif_record_start, ivRecord);
                isStart = true;
            } else {
                if (isBind) {
                    destoryRecord();
                } else {
                    stopRecord();
                }
            }

        } else {
            //显示停止录音的状态
            ImageUtils.loadImage(BoundDetailActivity.this, R.drawable.image_record_able, ivRecord);
            isStart = false;
        }
        if (EmptyUtils.isNotEmpty(visitCaseDto) && EmptyUtils.isNotEmpty(visitCaseDto.getDto())) {
            if (visitCaseDto.getDto().getStatus() == 1 || visitCaseDto.getDto().getStatus() == 2) {
                /**
                 * 获取照片文件
                 */
                getPhotoFileOunt();

            }
        }

    }

    /**
     * 获取照片文件
     */
    private void getPhotoFileOunt() {
        LoginDto dto = SPUtil.getData(Constant.SP.SP, Constant.SP.LOGIN_KEY, LoginDto.class, null);
        String userCount = dto.getUserAccount();
        photoViewModel.getPhotoFilesCountById(visitCaseDto.getVisitApplyId(), userCount).observe(this, new Observer<List<VisitUserDto>>() {
            @Override
            public void onChanged(@Nullable List<VisitUserDto> visitUserDtos) {
                tvPhoto.setText(String.valueOf(visitUserDtos == null ? 0 : visitUserDtos.size()));
            }
        });
    }

    /**
     * 获取录音文件
     */
    private void getRecordFileCount() {
        LoginDto dto = SPUtil.getData(Constant.SP.SP, Constant.SP.LOGIN_KEY, LoginDto.class, null);
        String userCount = dto.getUserAccount();
        recordViewModel.getRecordFilesCountById(visitCaseDto.getVisitApplyId(), userCount).observe(this, new Observer<List<VisitUserDto>>() {
            @Override
            public void onChanged(@Nullable List<VisitUserDto> visitUserDtos) {
                tvRecording.setText(String.valueOf((visitUserDtos == null ? 0 : visitUserDtos.size())));
            }
        });
    }

    private RelativeLayout rlVisithouses;
    private RelativeLayout rlInnerdecorations;
    private RelativeLayout rlHouseappliances;
    private RelativeLayout rlLivingsituations;
    private RelativeLayout rlEmailsituations;
    private RelativeLayout rlRepaypowers;

    @Override
    public void initListener() {
        etVisitAddress.setOnClickListener(this);
        rlVisitAddress.setOnClickListener(this);
        llRecord.setOnClickListener(this);
        llPhoto.setOnClickListener(this);
        tvDefault.setOnClickListener(this);
        tvCustom.setOnClickListener(this);
        ivNoYes.setOnClickListener(this);
        etVisitTime.setOnClickListener(this);
        etAssistCommissioner.setOnClickListener(this);
        etAddressType.setOnClickListener(this);
        etVisitSituation.setOnClickListener(this);
        etVehicle.setOnClickListener(this);
        rlVisithouses.setOnClickListener(this);
        rlInnerdecorations.setOnClickListener(this);
        rlHouseappliances.setOnClickListener(this);
        rlLivingsituations.setOnClickListener(this);
        rlEmailsituations.setOnClickListener(this);
        rlRepaypowers.setOnClickListener(this);
        llRecordFile.setOnClickListener(this);
        llPhotoFile.setOnClickListener(this);

    }


    @Override
    protected void onStop() {
        super.onStop();
    }


    private boolean isBind;

    /**
     * 开始录音
     */
    private void startRecord() {
        startService(intentService);
        bindService(intentService, conn, BIND_AUTO_CREATE);
        isBind = true;
    }

    /**
     * 停止录音
     */
    private void stopRecord() {
        stopService(intentService);
    }

    /**
     * 停止录音
     */
    private void destoryRecord() {
        unbindService(conn);
        stopService(intentService);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_photo:
                        takePhoto = getTakePhoto();
                        CropOptions.Builder builder = new CropOptions.Builder();
                        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
                        File file = new File(Environment.getExternalStorageDirectory() + "/temp/" +
                                timeStamp + ".jpg");
                        setFileName(timeStamp);

                        if (!file.getParentFile().exists()) {
                            boolean mkdirs = file.getParentFile().mkdirs();
                            if (!mkdirs) {
                                Log.e(TAG, "initView: 创建目录失败");
                            }
                        }
                        Uri imageUri = Uri.fromFile(file);
                        takePhoto.onPickFromCapture(imageUri);
                break;
            case R.id.ll_record:
                if (!isStart) {
                    startRecord();

                } else {
                    if (isBind) {
                        destoryRecord();
                    } else {
                        stopRecord();
                    }
                }
                break;
            case R.id.et_visit_address:
                getLoadingDialog().showDialog();
                new Thread() {
                    @Override
                    public void run() {
                        CityPickerView pickerView = getPickerInstance();
                        Message message = Message.obtain();
                        message.obj = pickerView;
                        message.what = 1001;
                        handler.sendMessage(message);
                    }
                }.start(

                );

                break;
            case R.id.tv_custom:
                isDefaut = false;
                tvCustom.setBackgroundResource(R.drawable.shape_button_select_bg);
                tvDefault.setBackgroundResource(R.drawable.shape_input_to_visit);
                tvCustom.setTextColor(Color.parseColor("#FFFFFF"));
                tvDefault.setTextColor(Color.parseColor("#999999"));
                etVisitAddress.setText(null);
                etStreetAddres.setText(null);
                etAddressType.setText(null);
                rlStreetAddress.setVisibility(View.VISIBLE);
                etVisitAddress.setEnabled(true);
                etAddressType.setEnabled(true);
                break;
            case R.id.tv_default:
                isDefaut = true;
                tvCustom.setBackgroundResource(R.drawable.shape_input_to_visit);
                tvDefault.setBackgroundResource(R.drawable.shape_button_select_bg);
                tvCustom.setTextColor(Color.parseColor("#999999"));
                tvDefault.setTextColor(Color.parseColor("#FFFFFF"));
                etVisitAddress.setText(dto.getAddress());
                etStreetAddres.setText(null);
                etAddressType.setText(dto.getAddressType());
                rlStreetAddress.setVisibility(View.GONE);
                etVisitAddress.setEnabled(false);
                etAddressType.setEnabled(false);
                break;
            case R.id.iv_no_yes:
                if (isKnow) {
                    ivNoYes.setImageResource(R.drawable.image_no);
                    isKnow = false;
                    etDescription.setVisibility(View.GONE);
                } else {
                    ivNoYes.setImageResource(R.drawable.image_yes);
                    etDescription.setVisibility(View.VISIBLE);
                    isKnow = true;
                }

                break;
            //地址类型
            case R.id.et_address_type:
                new SelectTypeDailog(this, this).showSelectAddressTypeDailog();
                break;
            //外访情况
            case R.id.et_visit_situation:
                new SelectTypeDailog(this, this).showSelectVisitSituationDailog();
                break;
            //交通工具
            case R.id.et_vehicle:
                new SelectTypeDailog(this, this).showSelectVehicleDailog();
                break;
            case R.id.et_visit_time:
                Calendar now = Calendar.getInstance();
                now_year = now.get(Calendar.YEAR);
                now_month = now.get(Calendar.MONTH) + 1;
                //年月日
                selectTimeDailog = new SelectTimeDailog(this, this);
                selectTimeDailog.showSelectYearMonthDayDialog(now_year, now_month);
                break;
            case R.id.et_assist_commissioner:
                new SelectAssistCommissionerWindow(this, this).showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                break;
            //显示隐藏
            case R.id.rl_visithouses:
                if (rvVisithouses.getVisibility() == View.VISIBLE) {
                    rvVisithouses.setVisibility(View.GONE);
                } else {
                    rvVisithouses.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rl_innerdecorations:
                if (rvInnerdecorations.getVisibility() == View.VISIBLE) {
                    rvInnerdecorations.setVisibility(View.GONE);
                } else {
                    rvInnerdecorations.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rl_houseappliances:
                if (rvHouseappliances.getVisibility() == View.VISIBLE) {
                    rvHouseappliances.setVisibility(View.GONE);
                } else {
                    rvHouseappliances.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rl_livingsituations:
                if (rvLivingsituations.getVisibility() == View.VISIBLE) {
                    rvLivingsituations.setVisibility(View.GONE);
                } else {
                    rvLivingsituations.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rl_emailsituations:
                if (rvEmailsituations.getVisibility() == View.VISIBLE) {
                    rvEmailsituations.setVisibility(View.GONE);
                } else {
                    rvEmailsituations.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rl_repaypowers:
                if (rvRepaypowers.getVisibility() == View.VISIBLE) {
                    rvRepaypowers.setVisibility(View.GONE);
                } else {
                    rvRepaypowers.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.ll_photo_file:
                toUpLoadFileActivity(visitCaseDto.getDto().getStatus(), 1);
                break;
            case R.id.ll_record_file:
                toUpLoadFileActivity(visitCaseDto.getDto().getStatus(), 0);
                break;


        }


    }


    private View parentView;
    private boolean isDefaut = true;
    private SelectTimeDailog selectTimeDailog;
    private int now_year;
    private int now_month;
    private boolean isKnow = true;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1001:
                    getLoadingDialog().dismiss();
                    CityPickerView pickerView = (CityPickerView) msg.obj;
                    pickerView.showCityPicker();
                    //监听选择点击事件及返回结果
                    pickerView.setOnCityItemClickListener(new OnCityItemClickListener() {
                        @Override
                        public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {

                            //省份
                            if (province != null) {

                            }

                            //城市
                            if (city != null) {

                            }

                            //地区
                            if (district != null) {

                            }
                            etVisitAddress.setText(province.getName() + city.getName() + district.getName());

                        }

                        @Override
                        public void onCancel() {
                            ToastUtils.showToast("已取消");
                        }
                    });
                    break;

                case 800:
                    getPhotoFileOunt();
                    break;
            }
        }
    };

    /**
     * 构造上传实体
     *
     * @param type 文件类型
     */
    private VisitUserDto getVisitUserDto(String type, String fileName) {
        LoginDto dto = SPUtil.getData(Constant.SP.SP, Constant.SP.LOGIN_KEY, LoginDto.class, null);
        VisitUserDto visitUserDto = new VisitUserDto();
        //用户名
        visitUserDto.setUserAccount(dto == null ? "" : dto.getUserAccount());
        visitUserDto.setFileName(fileName);
        visitUserDto.setUploadStatus("1");//上传状态
        visitUserDto.setFileType(type);//文件类型
        visitUserDto.setName(visitCaseDto.getName());//被仿人姓名
        visitUserDto.setVisitApplyId(String.valueOf(visitCaseDto.getDto().getId()));//外访id
        visitUserDto.setFileAdress(fileAdress);//文件生成地址
        visitUserDto.setTaskAdress(visitCaseDto.getDto().getVisitAddress());//任务分配，外访地址（动态）
        visitUserDto.setTaskTime(visitCaseDto.getTaskTime());//任务分配时间
        visitUserDto.setFileTime(DateUtil.coverDateFormat(DateUtil.DEFAULT_DATE_FORMATTER, new Date()));//文件生成时间
        //时间，用来做文件名
        visitUserDto.setTime(DateUtil.coverDateFormat("yyyyMMddHHmmss", new Date()));
        return visitUserDto;
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation != null) {
            //获取定位地址
            fileAdress = bdLocation.getAddrStr();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            //相机回调
            if (requestCode == FROM_CAPTURE && resultCode == -1) {


            } else if (requestCode == 1001) {
                initCaseView(1001);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private List<File> recordFiles;

    /**
     * 获取待上传的录音文件
     */
    private void initRecordData() {
        recordFiles = new ArrayList<>();
        recordViewModel.getFileCountLiveData().observe(this, new Observer<List<File>>() {
            @Override
            public void onChanged(@Nullable List<File> files) {
                recordFiles.addAll(files);
            }
        });
    }

    private List<File> photoFiles;

    /**
     * 获取待上传的图片文件
     */
    private void initPhotoData() {
        photoFiles = new ArrayList<>();
        photoViewModel.getFileCountLiveData().observe(this, new Observer<List<File>>() {
            @Override
            public void onChanged(@Nullable List<File> files) {
                photoFiles.addAll(files);
            }
        });
    }

    @Override
    public void onSelectVisitHouse(int position) {
        visithouseDtoList.get(position).setSelect(!visithouseDtoList.get(position).isSelect());
        if (visithouseDtoList.get(position).isSelect()) {
            for (int i = 0; i < visithouseDtoList.size(); i++) {
                if (i != position) {
                    visithouseDtoList.get(i).setSelect(false);
                }
            }
        }
        vsitHouseAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSelectInnerdecorations(int position) {
        innerDecorationList.get(position).setSelect(!innerDecorationList.get(position).isSelect());
        if (innerDecorationList.get(position).isSelect()) {
            for (int i = 0; i < innerDecorationList.size(); i++) {
                if (i != position) {
                    innerDecorationList.get(i).setSelect(false);
                }
            }
        }
        innerdecorationseAdapter.notifyDataSetChanged();
    }

    //家用电器
    @Override
    public void onSelectHouseappliances(int position) {
        houseapplianceList.get(position).setSelect(!houseapplianceList.get(position).isSelect());
        houseapplianceAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSelectLivingsituations(int position) {
        livingsituationsList.get(position).setSelect(!livingsituationsList.get(position).isSelect());
        if (livingsituationsList.get(position).isSelect()) {
            for (int i = 0; i < livingsituationsList.size(); i++) {
                if (i != position) {
                    livingsituationsList.get(i).setSelect(false);
                }
            }
        }
        livingsituationsAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSelectVisithousesSize(int position) {
        visithousesSizeList.get(position).setSelect(!visithousesSizeList.get(position).isSelect());
        if (visithousesSizeList.get(position).isSelect()) {
            for (int i = 0; i < visithousesSizeList.size(); i++) {
                if (i != position) {
                    visithousesSizeList.get(i).setSelect(false);
                }
            }
        }
        visithousesSizeAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSelectRepaypowers(int position) {
        repaypowersList.get(position).setSelect(!repaypowersList.get(position).isSelect());
        if (repaypowersList.get(position).isSelect()) {
            for (int i = 0; i < repaypowersList.size(); i++) {
                if (i != position) {
                    repaypowersList.get(i).setSelect(false);
                }
            }
        }
        repaypowersAdapter.notifyDataSetChanged();
    }

    //信箱情况
    @Override
    public void onSelectEmailsituations(int position) {
        emailsituationsList.get(position).setSelect(!emailsituationsList.get(position).isSelect());
        if (emailsituationsList.get(position).isSelect()) {
            for (int i = 0; i < emailsituationsList.size(); i++) {
                if (i != position) {
                    emailsituationsList.get(i).setSelect(false);
                }
            }
        }
        emailsituationsAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSelectYearMonthDayHourMin(String date) {
        etVisitTime.setText(date);
    }

    private UserBean assistcommissioner;

    @Override
    public void onSelectAssistCommissioner(UserBean assistcommissioner) {
        this.assistcommissioner = assistcommissioner;
        etAssistCommissioner.setText(assistcommissioner.getUserName());


    }

    @Override
    public void selectAddress(String addressType) {
        etAddressType.setText(addressType);
    }

    @Override
    public void selectVehicle(String vehicle) {
        etVehicle.setText(vehicle);
    }

    @Override
    public void selectVehicleVisitSituation(String visitSituation) {
        etVisitSituation.setText(visitSituation);
    }


    private boolean isSave;

    /**
     * @param flag null为保存
     *             1 为完成外访
     */
    private void saveVisitRecord(final Integer flag) {

        //正在保存
        if (isSave) {
            return;
        }
        //判断是否在录音
        if (isStart) {
            ToastUtils.showToast("请结束录音再进行操作");
            return;
        }
        SaveVisitRecordVo vo = new SaveVisitRecordVo();
        //设置点击时候的外访开始时间
        vo.setBeginTime(beginTime);
        if (EmptyUtils.isNotEmpty(flag) && flag == 1)
        {

            if (TextUtils.isEmpty(etAddressType.getText().toString())) {
                ToastUtils.showToast("请选择地址类型");
                return;
            }

            if (TextUtils.isEmpty(etVisitAddress.getText().toString())) {
                ToastUtils.showToast("请选择外地址");
                return;
            }
            if (TextUtils.isEmpty(etVisitSituation.getText().toString())) {
                ToastUtils.showToast("请选择外访情况");
                return;
            }
            if (TextUtils.isEmpty(etCasedevelopment.getText().toString())) {
                ToastUtils.showToast("请输入外访催记");
                return;
            }
            //如果是自定义 必须要填街道地址
            if (!isDefaut && TextUtils.isEmpty(etStreetAddres.getText().toString())) {
                ToastUtils.showToast("请输入街道详细地址");
                return;
            }
            if(TextUtils.isEmpty(fileAdress)){
                vo.setVisitEndAddress(isDefaut ? dto.getVisitAddress() : (etVisitAddress.getText().toString() + "-" + etStreetAddres.getText().toString()));
            }
            else{
                vo.setVisitEndAddress(fileAdress);
            }

        }
        vo.setId(id);
        vo.setVisitTimeStr(etVisitTime.getText().toString());

        vo.setAssistId(this.assistcommissioner == null ? null : assistcommissioner.getId());
        //地址类型
        vo.setAddressType( etAddressType.getText().toString());
        //外访地址
        vo.setVisitAddress(isDefaut ? dto.getVisitAddress() : (etVisitAddress.getText().toString() + "-" + etStreetAddres.getText().toString()));
        //外访情况
        vo.setVisitSituation(visitSituationList.indexOf(etVisitSituation.getText().toString()));
        //交通工具
        vo.setVehicle(etVehicle.getText().toString());
        if (!TextUtils.isEmpty(etVehiclefee.getText().toString())) {
            vo.setVehicleFee(Double.parseDouble(etVehiclefee.getText().toString()));
        }
        vo.setNewContact(etNewContact.getText().toString());
        vo.setNewAddress(etNewAddress.getText().toString());
        vo.setCaseDevelopment(etCasedevelopment.getText().toString());
        vo.setNextStep(etNextStep.getText().toString());
        //如果不认识，就不提交邻居描述
        vo.setDescription(isKnow ? etDescription.getText().toString() : "");
        //邻居是否认识
        vo.setIsKown(isKnow ? 1 : 0);

        //外访房屋
        for (int i = 0; i < visithouseDtoList.size(); i++) {
            if (visithouseDtoList.get(i).isSelect()) {
                vo.setVisitHouse(visithouseDtoList.get(i).getValue());
                break;
            }
        }
        //室内装修
        for (int i = 0; i < innerDecorationList.size(); i++) {
            if (innerDecorationList.get(i).isSelect()) {
                vo.setInnerDecoration(innerDecorationList.get(i).getValue());
                break;
            }
        }
        //居住情况
        for (int i = 0; i < livingsituationsList.size(); i++) {
            if (livingsituationsList.get(i).isSelect()) {
                vo.setLivingSituation(livingsituationsList.get(i).getValue());
                break;
            }
        }
        //还款能力
        for (int i = 0; i < repaypowersList.size(); i++) {
            if (repaypowersList.get(i).isSelect()) {
                vo.setRepayPower(repaypowersList.get(i).getValue());
                break;
            }
        }
        String houseapplianceListStr = "";
        //只有加家用电器和信箱情况是多选
        for (int i = 0; i < houseapplianceList.size(); i++) {
            if (houseapplianceList.get(i).isSelect()) {
                if (TextUtils.isEmpty(houseapplianceListStr)) {
                    houseapplianceListStr += houseapplianceList.get(i).getValue();
                } else {
                    houseapplianceListStr += "," + houseapplianceList.get(i).getValue();
                }
            }

        }
        vo.setHouseAppliance(houseapplianceListStr);

        String emailSituationStr = "";
        //只有加家用电器和信箱情况是多选
        for (int i = 0; i < emailsituationsList.size(); i++) {
            if (emailsituationsList.get(i).isSelect()) {
                if (TextUtils.isEmpty(emailSituationStr)) {
                    emailSituationStr += emailsituationsList.get(i).getValue();
                } else {
                    emailSituationStr += "," + emailsituationsList.get(i).getValue();
                }
            }
        }
        vo.setEmailSituation(emailSituationStr);
        vo.setFileTotal((Integer.parseInt(tvPhoto.getText().toString()) + Integer.parseInt(tvRecording.getText().toString())));
        vo.setCaseId(dto.getCaseId());
        vo.setCaseManageId(dto.getCaseManageId());
        vo.setVisitApplyId(dto.getId());
//        vo.setAddressType(dto.getAddressType());
        vo.setFlag(flag);//点击完成外访传入，传 1
        if (flag != null && flag == 1) {
            vo.setEndTime(DateUtil.coverDateFormat(DateUtil.DEFAULT_DATE_FORMATTER, new Date()));

        }
        vo.setTaskCode(dto.getTaskId());
        getLoadingDialog().showDialog();
        isSave = true;

        //保存外访记录
        String json = JSONObject.toJSONString(vo);

        SaveVisitRecordBean saveVisitRecordBean = JSONObject.parseObject(json, SaveVisitRecordBean.class);

        new Thread() {
            @Override
            public void run() {
                super.run();
                isSave = false;
                getLoadingDialog().dismiss();
                AppDataBase appDataBase = AppDataBase.getInstance(BoundDetailActivity.this);
                VisitRecordDao visitRecordDao = appDataBase.getVisitRecord();
                SaveVisitRecordBean visitRecordBean = visitRecordDao.findVisitRecordDetail(saveVisitRecordBean.getVisitApplyId());
                //外访开始时间
                saveVisitRecordBean.setVisitTimeStr(beginTime);
                //外访结速时间
                saveVisitRecordBean.setEndTime( DateUtil.coverDateFormat("yyyy-MM-dd HH:mm:ss", new Date()));

                saveVisitRecordBean.setType(StringUtils.isEmpty(saveVisitRecordBean.getVisitAddress()) ? 1 : 2);
                //
                saveVisitRecordBean.setAddressType(vo.getAddressType());
                saveVisitRecordBean.setVisitAddress(vo.getVisitAddress());
                saveVisitRecordBean.setVisitSituation(vo.getVisitSituation());
                saveVisitRecordBean.setVehicle(vo.getVehicle());
                saveVisitRecordBean.setVehicleFee(vo.getVehicleFee());
                saveVisitRecordBean.setNewContact(vo.getNewContact());
                saveVisitRecordBean.setNewAddress(vo.getNewAddress());
                saveVisitRecordBean.setCaseDevelopment(vo.getCaseDevelopment());
                saveVisitRecordBean.setNextStep(vo.getNextStep());
                saveVisitRecordBean.setDescription(vo.getDescription());
                saveVisitRecordBean.setIsKown(vo.getIsKown());
                saveVisitRecordBean.setVisitHouse(vo.getVisitHouse());
                saveVisitRecordBean.setInnerDecoration(vo.getInnerDecoration());
                saveVisitRecordBean.setLivingSituation(vo.getLivingSituation());
                saveVisitRecordBean.setRepayPower(vo.getRepayPower());
                saveVisitRecordBean.setHouseAppliance(vo.getHouseAppliance());
                saveVisitRecordBean.setEmailSituation(vo.getEmailSituation());



                if (visitRecordBean == null) {
                    visitRecordDao.insertViistRecord(saveVisitRecordBean);
                } else {
                    visitRecordDao.updateViistRecord(saveVisitRecordBean);
                }

                if (flag != null && flag == 1) {
                    //完成外访，更新状态
                    VisitDao visitDao = appDataBase.getVisitDao();
                    VisitApplyBean visitApplyBean = visitDao.queryVisitList(saveVisitRecordBean.getVisitApplyId());
                    visitApplyBean.setStatus(VisitStatusEnum.VISIT_YIWAIFANG.getCode());

                    visitDao.updateVisitApply(visitApplyBean);

                    //更新条数
                    VisitCountBean visitCountBean = visitDao.findVisitCountDetail();
                    visitCountBean.setWaitVisit((visitCountBean.getWaitVisit() == null ? 0 : visitCountBean.getWaitVisit()) - 1);
                    visitCountBean.setVisited((visitCountBean.getVisited() == null ? 0 : visitCountBean.getVisited()) + 1);
                    visitDao.updateVisitCount(visitCountBean);
                    toTaskListView();
                }
            }
        }.start();

        getLoadingDialog().dismiss();
        if (flag != null && flag == 1) {
            ToastUtils.showToast("完成外访");

        } else {
            ToastUtils.showToast("保存成功");
        }

    }

    /**
     * 跳转到任务列表界面
     */
    private void toTaskListView() {
        finish();
        CcsApplication.clearSpecifyActivities(
                new Class[]{
                        CaseInformationActivity.class,
                        OutBoundtaskListActivity.class,
                        TaskTripMapActivity.class,
                        BusListPlanActivity.class,
                        BusPlanDetailActivity.class});
        Intent intent = new Intent(BoundDetailActivity.this, OutBoundtaskListActivity.class);
        startActivity(intent);
    }


    @Override
    protected void onPause() {
        super.onPause();
    }


    /**
     * 监听如果是电话来了 就停止录音
     *
     * @param str
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void callListener(String str) {

        if (!TextUtils.isEmpty(str) && "startRecord".equals(str)) {
            ToastUtils.showToast("正在录音");
            isStart = true;
            ImageUtils.loadImage(BoundDetailActivity.this, R.drawable.gif_record_start, ivRecord);
        }
        if (!TextUtils.isEmpty(str) && "stopRecord".equals(str)) {
            // ToastUtils.showToast("停止录音");
            isStart = false;
            ImageUtils.loadImage(BoundDetailActivity.this, R.drawable.image_record_able, ivRecord);
            getRecordFileCount();

        }
    }

    private class MyConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            getRecordFileCount();
            //只有当我们自己写的MyService的onBind方法返回值不为null时，才会被调用
            Log.e(TAG, "onServiceConnected");
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            recorderUtil = new RecorderUtil(getVisitUserDto("1", timeStamp), timeStamp);
            //调用服务中的方法
            ((RecordServcie.MyBinder) service).startRecording(recorderUtil, visitCaseDto.getDto().getId());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //这个方法只有出现异常时才会调用，服务器正常退出不会调用。
            Log.e(TAG, "onServiceDisconnected");
        }

    }


    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param mContext
     * @param serviceName 是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }




}
